package com.pucheng.bracelet.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;

import com.pucheng.bracelet.R;
import com.pucheng.bracelet.data.bean.SleepBean;
import com.pucheng.bracelet.data.bean.SleepNode;

/**
 * Created by daimajia on 14-4-30.
 */
public class SleepProgressBar extends View {

    private int mMaxProgress = 100;

    /**
     * Current progress, can not exceed the max progress.
     */
    private int mCurrentProgress = 0;

    /**
     * The progress area bar color.
     */
    private int mReachedBarColor;

    /**
     * The height of the reached area.
     */
    private float mReachedBarHeight;

    /**
     * The height of the unreached area.
     */

    private final int default_reached_color = Color.rgb(66, 145, 241);
    private final float default_reached_bar_height;

    /**
     * For save and restore instance of progressbar.
     */
    private static final String INSTANCE_STATE = "saved_instance";
    private static final String INSTANCE_REACHED_BAR_HEIGHT = "reached_bar_height";
    private static final String INSTANCE_REACHED_BAR_COLOR = "reached_bar_color";
    private static final String INSTANCE_MAX = "max";
    private static final String INSTANCE_PROGRESS = "progress";

    /**
     * The Paint of the reached area.
     */
    private Paint mReachedBarPaint;
    /**
     * Reached bar area rect.
     */
    private RectF mReachedRectF = new RectF(0, 0, 0, 0);

    private SleepBean sleepInfoBean;



    public SleepProgressBar(Context context) {
        this(context, null);
    }

    public SleepProgressBar(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.numberProgressBarStyle);
    }

    public SleepProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        default_reached_bar_height = dp2px(10f);
        //load styled attributes.
        final TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.NumberProgressBar,
                defStyleAttr, 0);

        mReachedBarColor = attributes.getColor(R.styleable.NumberProgressBar_progress_reached_color, default_reached_color);

        mReachedBarHeight = attributes.getDimension(R.styleable.NumberProgressBar_progress_reached_bar_height, default_reached_bar_height);


        setProgress(attributes.getInt(R.styleable.NumberProgressBar_progress_current, 0));
        setMax(attributes.getInt(R.styleable.NumberProgressBar_progress_max, 100));

        attributes.recycle();
        initializePainters();
    }

    @Override
    protected int getSuggestedMinimumHeight() {
        return (int) (mReachedBarHeight );
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measure(widthMeasureSpec, true), measure(heightMeasureSpec, false));
    }

    private int measure(int measureSpec, boolean isWidth) {
        int result;
        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);
        int padding = isWidth ? getPaddingLeft() + getPaddingRight() : getPaddingTop() + getPaddingBottom();
        if (mode == MeasureSpec.EXACTLY) {
            result = size;
        } else {
            result = isWidth ? getSuggestedMinimumWidth() : getSuggestedMinimumHeight();
            result += padding;
            if (mode == MeasureSpec.AT_MOST) {
                if (isWidth) {
                    result = Math.max(result, size);
                } else {
                    result = Math.min(result, size);
                }
            }
        }
        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (sleepInfoBean != null) {
            float lastLeft = getPaddingLeft();
            for (int i = 0; i < sleepInfoBean.getNodes().size(); i++) {
                SleepNode node = sleepInfoBean.getNodes().get(i);
                switch (node.getStatus()) {
                    case 1:
                        setReachedBarColor(getResources().getColor(R.color.color_light));
                        break;
                    case 2:
                        setReachedBarColor(getResources().getColor(R.color.color_restful));
                        break;
                    case 3:
                        setReachedBarColor(getResources().getColor(R.color.color_rem));
                        break;

                }
                initializePainters();
                mReachedRectF.left = lastLeft;
                mReachedRectF.top = getHeight() / 2.0f - mReachedBarHeight / 2.0f;
                mCurrentProgress = node.getMin_offset();
                lastLeft = (getWidth() - getPaddingLeft() - getPaddingRight()) / (getMax() * 1.0f) * getProgress() + getPaddingLeft();
                mReachedRectF.right = lastLeft;
                mReachedRectF.bottom = getHeight() / 2.0f + mReachedBarHeight / 2.0f;
//                if (i == 0 ) {
//                    Path path = new Path();
//                    path.moveTo(mReachedRectF.left,mReachedRectF.top);
//                    path.addArc(mReachedRectF,90,180);
//                }else if(i == (sleepInfoBean.getNodes().size()-1)){
//                    Path path = new Path();
//                    path.moveTo(mReachedRectF.left,mReachedRectF.top);
//                    path.addArc(mReachedRectF,90,180);
//                }else {
                    canvas.drawRect(mReachedRectF,mReachedBarPaint);
//                    canvas.drawRoundRect();
//                }
            }
        }
//        mCurrentDrawText = sleepInfoBean.getDate();
//        mDrawTextWidth = mTextPaint.measureText(mCurrentDrawText);
//
//        if (getProgress() == 0) {
//            mDrawReachedBar = false;
//            mDrawTextStart = getPaddingLeft();
//        } else {
//            mDrawReachedBar = true;
////            mReachedRectF.left = getPaddingLeft();
////            mReachedRectF.top = getHeight() / 2.0f - mReachedBarHeight / 2.0f + mReachedBarHeight;
////            mReachedRectF.right = (getWidth() - getPaddingLeft() - getPaddingRight()) / (getMax() * 1.0f) * getProgress() - mOffset + getPaddingLeft();
////            mReachedRectF.bottom = getHeight() / 2.0f + mReachedBarHeight / 2.0f+ mReachedBarHeight;
//            mDrawTextStart = (mReachedRectF.right + mOffset);
//        }
//
//        mDrawTextEnd = (int) ((getHeight() / 2.0f) - ((mTextPaint.descent() + mTextPaint.ascent()) / 2.0f));
//
//        if ((mDrawTextStart + mDrawTextWidth) >= getWidth() - getPaddingRight()) {
//            mDrawTextStart = getWidth() - getPaddingRight() - mDrawTextWidth;
////            mReachedRectF.right = mDrawTextStart - mOffset;
//        }
//        canvas.drawText(mCurrentDrawText, mDrawTextStart, mDrawTextEnd, mTextPaint);

    }

    private void initializePainters() {
        mReachedBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mReachedBarPaint.setColor(mReachedBarColor);
    }

    public int getReachedBarColor() {
        return mReachedBarColor;
    }

    public int getProgress() {
        return mCurrentProgress;
    }

    public int getMax() {
        return mMaxProgress;
    }

    public float getReachedBarHeight() {
        return mReachedBarHeight;
    }

    public void setReachedBarColor(int progressColor) {
        this.mReachedBarColor = progressColor;
        mReachedBarPaint.setColor(mReachedBarColor);
        invalidate();
    }

    public void setReachedBarHeight(float height) {
        mReachedBarHeight = height;
    }

    public void setMax(int maxProgress) {
        if (maxProgress > 0) {
            this.mMaxProgress = maxProgress;
            invalidate();
        }
    }

    public void incrementProgressBy(int by) {
        if (by > 0) {
            setProgress(getProgress() + by);
        }

    }

    public void setSleepInfo(SleepBean bean) {
        if (bean != null) {
            this.sleepInfoBean = bean;
            setMax(bean.getTotalTime());
            invalidate();
        }
    }

    public void setProgress(int progress) {
        if (progress <= getMax() && progress >= 0) {
            this.mCurrentProgress = progress;
            invalidate();
        }
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        final Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE_STATE, super.onSaveInstanceState());
        bundle.putFloat(INSTANCE_REACHED_BAR_HEIGHT, getReachedBarHeight());
        bundle.putInt(INSTANCE_REACHED_BAR_COLOR, getReachedBarColor());
        bundle.putInt(INSTANCE_MAX, getMax());
        bundle.putInt(INSTANCE_PROGRESS, getProgress());
        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            final Bundle bundle = (Bundle) state;
            mReachedBarHeight = bundle.getFloat(INSTANCE_REACHED_BAR_HEIGHT);
            mReachedBarColor = bundle.getInt(INSTANCE_REACHED_BAR_COLOR);
            initializePainters();
            setMax(bundle.getInt(INSTANCE_MAX));
            setProgress(bundle.getInt(INSTANCE_PROGRESS));
            super.onRestoreInstanceState(bundle.getParcelable(INSTANCE_STATE));
            return;
        }
        super.onRestoreInstanceState(state);
    }

    public float dp2px(float dp) {
        final float scale = getResources().getDisplayMetrics().density;
        return dp * scale + 0.5f;
    }

//    public float sp2px(float sp) {
//        final float scale = getResources().getDisplayMetrics().scaledDensity;
//        return sp * scale;
//    }
}
